<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>本地取歌</title>
    <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <!--标准 mui.css-->
    <!--App 自定义的 css-->
    <style>
        ul, ol {
            list-style: none;
            margin: 0;
            padding: 0;
        }

        #box {
            width: 300px;
            /*margin: 50px auto;*/
            /*position: relative;*/
            padding: 40px 0 10px 10px;
            position: fixed;
            background-color:white;
            z-index: 111;
        }

        #txtSearch {
            width:200px;
            height:1.2em;
            line-height:24px;
            padding:5px 8px;
            float: right;
            margin-top: -5px;
            /*border-right: 0;*/
        }
        #b{
            width:80px;
            padding:1px 8px;
            float: right;
        }
        .input{
            border: 1px solid #b6b6b6;
            width: 90px;
        }
        .input:empty::before {
            content: attr(placeholder);
        }
        button {
            float: left;
            width: 150px;
            height: 34px;
            font: 400 14px/34px "microsoft yahei";
            color: white;
            background: #3385ff;
            cursor: pointer;
            border:1px solid white;
        }

        button:hover {
            background: #317ef3;
        }
        #pop{
            float:right;
            width: 212px;
            height: 260px;
            border: 1px solid #ccc;
            padding: 2px;
            position: absolute;
            top: 65px;
            right:0;
            background-color:#ffffff;
            /*overflow:auto;*/
        }
        #pop ul{
            overflow: auto;
            width: 210px;
            height: 260px;
        }
        ul li {
            padding-bottom: 5px;
            padding-left: 5px;
        }

        #pop ul li:hover {
            background-color: #317ef3;
            color: #ffffff;
        }
        .rightBut{
            position: absolute;
            top: 35px;
            right: 0;
        }
        .combo-arrow{
            text-align: center;
            padding-top: 5px;
            outline-style: none;
            display: inline-block;
            background: url('https://img.icons8.com/material-outlined/2x/down-squared.png') no-repeat center center;
            width: 24px;
            height: 20px;
        }
        .footer{
            width: 150px;
            margin: 0 auto;
            position: fixed;
            bottom: 0;
            padding: 30px 30px 10px 30px;
            z-index: 1111;
            right: 0;
            background-color:white;
        }
        form{
            width: 100%;
            font-size: 1em;
            position: absolute;
            top: 0;
            left: 0;
            height: 100%;
        }
        #c{
            position: absolute;
        }
        label{margin-left: 34px;}
        #collect{
            width: 206px;
            height:200px;
            margin: 110px 0 10px 92px;
            position: absolute;
            border: 1px solid #ccc;
            padding: 10px 0 10px 10px;
        }
        #changeCollect{
            width: 7em;
            height: 33px;
            margin: 30px 0 10px 0;
            position: absolute;
        }
        #cc{
            overflow: auto;
            width: 200px;
            height: 200px;
        }
    </style>
    <script>
        function get(url,fun,d){
            var xhr = new XMLHttpRequest();
            xhr.open("GET", url, true);
            xhr.setRequestHeader("Content-type", "application/json");
            xhr.onreadystatechange = function () {
                var XMLHttpReq = xhr;
                if (XMLHttpReq.readyState == 4) {
                    if (XMLHttpReq.status == 200) {
                        return fun( XMLHttpReq.responseText)
                    } else {
                        console.log(XMLHttpReq.status)
                    }
                } else {
                    console.log(XMLHttpReq.readyState);
                }
            }
            xhr.send(d)
        }
        function xhrsend(d) {
            get('/set_event',
                function (text) {
                    console.log(text);
                }, d ? `{"name": "r","value":"${d}"}` : '{"name": "showUI_cancel"}')
        }

        var isChange=false//是否改变显示，改变时重新加载显示内容而不是运行脚本
        var pinyin=null//先定义下拼音变量，以防加载失败时报错
    </script>
    <script src="http://yinyingyang.gitee.io/js/pinyin.js"></script>
</head>

<body id="c">
<!--div style="position: fixed;
            top: 20px;
            z-index: 1111;
            margin: auto;
            right: 20px;"><input id="no" type="button" value="横/竖屏"/></div-->
<form id="form" name="showUI_commit" method="post" action="/set_event">

    <div id="box">
        <span class="rightBut">
            <span class="combo-arrow" icon-index="0" tabindex="-1"></span>
        </span>
        <label>选歌：</label><input placeholder="支持歌名、拼音、首字母搜索" id="txtSearch"class="input" contenteditable="true" value="随机播放"/><button id="changeCollect" type="button">加入收藏</button>
        <!--<input type="button" value="搜索" id="btnSearch">-->
    </div>
    <div id="collect">
        <ul id="cc"></ul>
        <textarea id='error' style='width:200px;display: none;height: 100px;margin-top: 10px;margin-left: -10px;'>1</textarea>
    </div>
    <script>
        var v='v0'
        window.onerror = function(message,url,line){
            // 汇报错误
            var e=document.getElementById("error")
            e.innerHTML =v+"执行" + url + "文件中的第" + line + "行代码出错，错误信息：" + message;
            e.style.display=""
            window.onerror = null;
            // 不希望此错误继续扩散
            return true;
        };
    </script>
    <br>
    <br>
    <div class="footer">
        <p><input type="checkbox" name="item" ><label>无悬浮键</label></p>
        <p><input type="checkbox" name="item"><label>多弹</label></p>
        <p><input type="checkbox" name="item"><label>按键初始化</label></p>
        <p>HOME键：<select id="rotate"></select></p>
        <p>速度：<select id="speed"></select></p>
        <button id="actions" type="button">弹奏</button>
        <button id="cancel" type="button">取消</button>

    </div>

</form>
<p id="test"></p>
<script type="text/javascript">
    document.getElementById('cancel').onclick = function () {//取消按钮点击
        xhrsend();
    }

    var box = document.getElementById("box");
    var txt = document.getElementById("txtSearch");
    var namesPY=[];//拼音

    //加载区，从lua加载相关数据，同时方便修改测试
        var names = "一,二,三,四,五,六,七,八".split(',');
        loadRotate=0
        var collect="一^二^三";
        var collects= collect.split('^');
        var bs=`0,1,2,3,4`.split(',')
        var otherLength=0;
        var music=5;//选的歌

    //加载区，从lua加载相关数据，同时方便修改测试
//    var names = "]]..musicStr..[[".split(',');
//    var loadRotate=]]..(r.rotate)..[[;
//    var collect="]]..r.collect..[[";
//    var collects= collect.split('^');
//    var bs=`]]..array2str(sTimeList,'默认')..[[`.split(',')
//    var otherLength=]]..#otherSe..[[;
//    var music=]]..(r.i-1)..[[;//选的歌

    //初始化速度选择
    var bStr="";
    for(i=0;i<bs.length;i++){
        bStr+=`<option value=${i}${bs==i?' selected':''}>${bs[i]}</option>`
    }
    document.getElementById("speed").innerHTML=bStr;
    //初始化方向
    var rStr='';
    rotates=['在下','在右','在左']
    for(i=0;i<3;i++){
        rStr+=`<option value=${i}${loadRotate==i?' selected':''}>${rotates[i]}</option>`
    }
    rotateE=document.getElementById("rotate")
    rotateE.innerHTML=rStr;
    rotateE.addEventListener("change", function(){isChange=1;commit()});

    var pop=null//歌曲列表
    var isrotate=1//旋转状态，0竖
    //初始化收藏
    var colInt=[]
    initCollect=()=> {
        var cc = document.getElementById("cc");
        cc.innerHTML=""
        for (i = 0; i < collects.length; i++) {
            let index=names.indexOf(collects[i])
            if(index==-1)
                collects.splice(i,1)
            else {
                var li = document.createElement("li");
                cc.appendChild(li);
                li.innerText = collects[i];
                colInt.push(index)
                li.setAttribute('music', index)
            }
        }
        cc.onclick = l => {
            l = l.toElement;
            txt.value = l.innerText;
            music = l.getAttribute('music')
            changeCollect.innerText='取消收藏'
        }
    }

    var changeCollect=document.getElementById('changeCollect')
    changeCollect.onclick = function () {//修改收藏
        if(music<otherLength)return;
        let m=names[music]
        let n = collects.indexOf(m);
        n==-1?
            (collects.push(m) ,colInt.push(music),changeCollect.innerText='取消收藏')
            :(collects.splice(collects.indexOf(m),1),colInt.splice(colInt.indexOf(music),1),changeCollect.innerText='加入收藏')
        initCollect()
    }
    //初始化音乐列表
    openClose=e=> {
        e.style.display == "none"?showE(e):hideE(e)
    }
    initMusic=()=>{
        if(pop)
            ul.innerHTML=""
        else {
            pop = document.createElement("div");
            pop.id = "pop";
            box.appendChild(pop);
            ul = document.createElement("ul");
            pop.appendChild(ul);
        }
        //2.2根据数组中的每一项数据创建li
        for (var i = 0; i < names.length; ++i) {
            var li = document.createElement("li");
            ul.appendChild(li);
            li.innerText = names[i];
            namesPY[i]=pinyin?pinyin.getCamelChars(names[i])+pinyin.getFullChars(names[i]).toUpperCase():""
            li.setAttribute('music',i)
            li.id=i;
        }
        ul.onclick=l=>{
            l=l.toElement;
            if(l.localName!='li')return
            txt.value=l.innerText;
            music=parseInt(l.getAttribute('music'));
            changeCollect.innerText=colInt.indexOf(music)>-1?'取消收藏':'加入收藏';
            openClose(pop)
        }
        openClose(pop)
    }
    showE=e=>{(e.style.display != "block")&&(e.style.display = "block")};
    hideE=e=>{(e.style.display != "none")&&(e.style.display = "none")};
    showAll=()=>{var li = document.getElementsByTagName("li");
        try{for(var e in li)showE(li[e])}catch (e){}};
    initMusic()

    input = function () {
        var val = txt.value;//获取当前文本框中的内容
        //没内容全显
        if (""==val) {
            showAll();
            return;
        }else{
            if(val.endsWith('\n\n')){
                val=txt.value=val.trim();
                txt.blur()
            }
        }
        var li = document.getElementsByTagName("li");
        //        try{for(var e in li)hideE(li[e])}catch (e){}
        showE(pop);
        var have=false;
        for (var i = 0; i < names.length; i++) {
            //判断每一个歌名是否包含val
            if (names[i].indexOf(val) > -1||namesPY[i].indexOf(val.toUpperCase()) > -1) {//符合要求
                showE(document.getElementById(i));
                have=true
            }else{
                hideE(document.getElementById(i))
            }
        }
        if (!have) {//一个都没，不显
            hideE(pop)
        }
    };
    //输入监听
    txt.addEventListener("input", input);
    txt.onclick=()=>{if(txt.value=='随机播放'||txt.value=='播放全部')txt.value=""};
    txt.ondblclick=()=>txt.value=''
    txt.value=names[music]
    let isChecked="";
    initChecked=()=>{
        var radioList = document.getElementsByName('item');
        for (var i = 0, len = radioList.length; i < len; i++) {
            if(isChecked.indexOf(i)>-1){
                radioList[i].checked =true
            }
        }
    };
    document.getElementsByClassName('combo-arrow')[0].onclick=()=>{openClose(pop);showAll();txt.value=""}
    checked=()=>{
        let str=' ';
        var radioList = document.getElementsByName('item');
        for (var i = 0, len = radioList.length; i < len; i++) {
            str+=radioList[i].checked ?i:""
        }
        return str
    };

    function actions(data) {//数据提交 post 请求    已作废
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "/set_event", true);
        xhr.setRequestHeader("Content-type", "application/json");
        xhr.onreadystatechange = function () {
            var XMLHttpReq = xhr;
            if (XMLHttpReq.readyState == 4) {
                if (XMLHttpReq.status == 200) {
                    var text = XMLHttpReq.responseText;
                    console.log(text);
                } else {
                    console.log(XMLHttpReq.status)
                }
            } else {
                console.log(XMLHttpReq.readyState);
            }
        };
        //alert('{"name": "showUI_commit","value":' + data + '}')
        xhr.send('{"name": "showUI_commit","value":"' + data + '"}');
    }


    function commit() {//数据提交按钮点击
        let t={}
        t.c=checked();
        t.b=document.getElementById("speed").value;
        t.music=music
        names[music].indexOf('.')>-1&&(t.name=names[music],
            t.txt=get('https://gitee.com/yinyingyang/music/raw/master/'+names[music],t=>{return t}))
        t.collect=collects.join("^")
        t.isChange=isChange
        t.colInt=colInt.join('^')
        t.rotate=document.getElementById("rotate").value;
        s=JSON.stringify(t);
        //s=s.substr(1,s.length-2)
        s=s.replace(/\"/g,'@')
        xhrsend(s);
    };
    document.getElementById('actions').onclick = commit
    //    document.getElementById('no').onclick = function () {//转屏
    //        isrotate?noRotate():rotate()
    //    }
    //    con = document.getElementById('c');
    width = document.documentElement.clientWidth;
    height = document.documentElement.clientHeight;
    //if(width<400||height<300)xhrsend(`显示过小,${width},${height}`)
    //function rotate() {
    //con.style.width = height + 'px';
    //con.style.height = width + 'px';
    //con.style.top = (height - width) / 2 + 'px';
    //con.style.left = 0 - (height - width) / 2 + 'px';
    //con.style.transform = loadRotate==2?'rotate(270deg)':'rotate(90deg)';
    //isrotate=1
    //}
    //    rotate()
    //function noRotate() {
    //con.style.width = width + 'px';
    //con.style.height = height + 'px';
    //con.style.top = '0px';
    //con.style.left = '0px';
    //con.style.transform = 'none';
    //isrotate=0
    //}
    function changeRotate() {
        loadRotate=loadRotate==2?1:2
        //isrotate&&
        xhrsend(loadRotate)
    }

    v='v201101'
    //   size=1
    //document.body.style.zoom = size;
    //document.body.style.cssText += '; -moz-transform: scale(' + size + ');-moz-transform-origin: 0 0; ';
    test=0


    function cloudMusic() {
        get("https://gitee.com/api/v5/repos/yinyingyang/music/git/trees/master", function(text) {
            let root = JSON.parse(text)
            let name = '', i = ''
            for (i of root.tree) {
                name = i.path
                if (names.indexOf(name.substr(0, name.length - 4)) == -1)
                    names.push(name)
            }
            initMusic()
            initCollect()
        })
//        get('https://gitee.com/yinyingyang/music/raw/master/'+path)
    }

    cloudMusic()
</script>
<!--script src="http://yinyingyang.gitee.io/js/localMusic.js?a=]]..math.random(100)..[["></script-->
</body>
</html>
